package cn.mldn.homework.multiThreadCountPrime;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Client extends AbstractFinder
{
	private int poolSize;// 创建线程的个数
	private int numberOfParts;// 任务的份数

	public Client(int poolSize, int numberOfParts)
	{
		this.poolSize = poolSize;
		this.numberOfParts = numberOfParts;
	}

	@Override
	public int multiThreadCountPrime(int number)
	{
		int num = 0;
		try
		{
			List<Callable<Integer>> partitions = new ArrayList<Callable<Integer>>();
			int chunksPerPartion = number / numberOfParts;

			for (int i = 0; i < numberOfParts; i++)
			{
				int startNumber = (i * chunksPerPartion) + 1;
				int endNumber = (i == numberOfParts - 1) ? number : startNumber + chunksPerPartion - 1;

				partitions.add(new Callable<Integer>()
				{
					@Override
					public Integer call()
					{
						return countPrime(startNumber, endNumber);
					}
				});
			}

			ExecutorService executorPool = Executors.newFixedThreadPool(poolSize);// 在线程池中创建线程
			List<Future<Integer>> resultFromParts = executorPool.invokeAll(partitions, 10000, TimeUnit.SECONDS);

			executorPool.shutdown();// 执行完成之后关闭线程池

			for (Future<Integer> result : resultFromParts)// 统计各任务的素数个数
				num += result.get();

		} catch (Exception ex)
		{
			throw new RuntimeException(ex);
		}

		return num;
	}

	public static void main(String[] args)
	{
		new Client(4, 4).countPrimeAndTime(10000000);
	}
}